package com.pearl.jacksoncore.demo.databind.objectmapper;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pearl.jacksoncore.demo.pojo.User;
import com.pearl.jacksoncore.demo.response.R;

import java.io.File;
import java.io.IOException;

/**
 * @author TD
 * @version 1.0
 * @date 2024/3/19
 */
public class ObjectMapperBaseTest {

    public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        // POJO->JSON
        User user = new User();
        user.setId(1767798780627279873L);
        user.setName("坤坤");
        user.setAge(18);
        String json = objectMapper.writeValueAsString(user);
        System.out.println(json);

        // 写入到文件
        File file = new File("E:\\TD\\pearl\\study-jackson-demo\\jackson-core-demo\\src\\main\\java\\com\\pearl\\jacksoncore\\demo\\file\\user.json");
        objectMapper.writeValue(file, user);

        // 文件读取JSON -> POJO
        User readUserByFile = objectMapper.readValue(file, User.class);
        System.out.println(readUserByFile);

        // 读取为树模型


        // 泛型擦除
        String jsonStr = "{\"code\":200,\"msg\":\"操作成功\",\"data\":{\"id\":1767798780627279873,\"name\":\"坤坤\",\"age\":18,\"org\":null,\"roleList\":[{\"id\":null,\"roleName\":\"管理员\",\"roleCode\":\"ROLE_ADMIN\"},{\"id\":null,\"roleName\":\"普通用户\",\"roleCode\":\"ROLE_USER\"}]}}";
        // R<User> response = objectMapper.readValue(jsonStr, R.class);
        R<User> response = objectMapper.readValue(jsonStr, new TypeReference<R<User>>() {
        });
        User data = response.getData();

        // 树模型
        String userJsonStr = "{\"id\":1767798780627279873,\"name\":\"坤坤\",\"age\":18,\"org\":null,\"roleList\":[{\"id\":null,\"roleName\":\"管理员\",\"roleCode\":\"ROLE_ADMIN\"},{\"id\":null,\"roleName\":\"普通用户\",\"roleCode\":\"ROLE_USER\"}]}";
        JsonNode jsonNode = objectMapper.readTree(userJsonStr);
        long userId = jsonNode.get("id").asLong();// 获取id 节点对应的值并转为 Long
        String userName = jsonNode.get("name").asText();// 获取 name 节点对应的值并转为 String
        String roleName = jsonNode.get("roleList").get(0).get("roleName").asText(); //  获取 roleList 节点对应的值，再获取第一个元素，再获取roleName 的值并转为 String

        System.out.println();
    }
}
